package codeRandomThoughts.Test134加油站;

import java.util.Arrays;

public class Solution2 {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int curSum=0;
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < gas.length; i++) {
            int rest = gas[i]-cost[i];
            curSum+=rest;

            //记录最多缺多少油
            if (curSum<min){
                min=curSum;
            }
        }

        //说明整体油不够
        if (curSum<0) return -1;

        //说明没有缺过油
        if (min>=0) return 0;

        //从后往前遍历,看从哪里开始能把缺的油给补上 补不上就返回false
        for (int i = gas.length-1; i >=0; i--) {
            int rest = gas[i]-cost[i];
            min+=rest;

            //如果能补上缺的油
            if (min>=0){
                return i;
            }
        }

        return -1;
    }
}
